"use client";
import React, { useCallback, useState } from "react";
import {
  Elements,
  LinkAuthenticationElement,
  PaymentElement,
  useElements,
  useStripe,
} from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import Image from "next/image";
import { formatCurrency } from "../lib/formatters";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "./ui/card";
import { Button } from "./ui/button";
import { isUserOrderExists } from "../actions/orders";

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY);

const Form = ({ priceInCents, id: productId }) => {
  const [isLoading, setIsLoading] = React.useState(false);
  const [errorMessage, setErrorMessage] = React.useState("");
  const [email, setEmail] = useState<string>();
  const stripe = useStripe();
  const elements = useElements();
  const onSubmit = useCallback(
    async (e) => {
      e.preventDefault();
      if (!stripe || !elements || !email) {
        return;
      }
      setIsLoading(true);
      // 检查是否有订单
      const isExist = await isUserOrderExists(email, productId);
      if (isExist) {
        setErrorMessage("You have already purchased this product");
        setIsLoading(false);
        return;
      }
      stripe
        .confirmPayment({
          elements,
          confirmParams: {
            return_url: `${process.env.NEXT_PUBLIC_SERVER_URL}/stripe/purchase-success`,
          },
        })
        .then(({ error }) => {
          if (error.message) {
            setErrorMessage(error.message);
          }
        })
        .finally(() => {
          setIsLoading(false);
        });
    },
    [stripe, elements, email, productId]
  );
  return (
    <form onSubmit={onSubmit}>
      <Card>
        <CardHeader>
          <CardTitle>Checkout</CardTitle>
          {errorMessage && (
            <CardDescription className="text-destructive">
              {errorMessage}
            </CardDescription>
          )}
        </CardHeader>
        <CardContent>
          <PaymentElement />
          <div className="mt-4">
            <LinkAuthenticationElement
              onChange={(e) => {
                setEmail(e.value.email);
              }}
            />
          </div>
        </CardContent>
        <CardFooter>
          <Button
            className="w-full"
            size="lg"
            disabled={!stripe || !elements || isLoading}
          >
            Purchase - {formatCurrency(priceInCents)}
          </Button>
        </CardFooter>
      </Card>
    </form>
  );
};

const CheckoutForm = ({ product, clientSecret }) => {
  return (
    <div className="max-w-5xl w-full mx-auto space-y-8">
      <div className="flex gap-4 items-center">
        <div className="relative aspect-video flex-shrink-0 w-1/3">
          <Image src={product.imagePath.slice(6)} fill alt={product.name} />
        </div>
        <div>
          <div className="text-lg">{formatCurrency(product.priceInCents)}</div>
          <h1 className="text-bold text-2xl">{product.name}</h1>
          <div className="line-clamp-3 text-muted-foreground">
            {product.description}
          </div>
        </div>
      </div>
      <Elements options={{ clientSecret }} stripe={stripePromise}>
        <Form {...product} />
      </Elements>
    </div>
  );
};

export default CheckoutForm;
